#!/bin/bash
#
# An example for a bashrc file.
#
# Maintainer:   Neiku <ku7d@qq.com>
# Last change:  2014 Dec 26
# 
# To use it, copy it to: ~/.bashrc
#                   and: source ~/.bashrc
#
# vim:ts=4:sw=4:expandtab
#

# alias
alias ..='cd ../'
alias ...='cd ../../'
alias ....='cd ../../../'
alias .....='cd ../../../../'
alias rm='rm'
alias cp='cp'
alias mv='mv'
#alias l='ls -l --color'
#alias ls='ls --color'
#alias ll='ls -l --color'
#alias la='ls -la --color'
alias grep='grep --color'
alias tree='tree -C'
alias kall='killall'

alias CD='cd'

# utf-8 to gbk, gbk to utf-8
alias u2g='iconv -f utf-8 -t gb18030//ignore'
alias g2u='iconv -f gbk -t utf-8//ignore'

# current host for openssh-server (5.3p1)
host="$(echo $SSH_CONNECTION | cut -f3 -d' ')"
if [ -z "$host" ]
then
    # for sshd-3.2.9.1
    host="$(echo $SSH2_CLIENT | cut -f3 -d' ')"
fi
if tty >/dev/null 2>&1
then
    neikurc="/tmp/.neikurc.$(tty | tr '/' '_')"
    if [ -n "$host" ]
    then
        echo "$host" > $neikurc
        chmod 666 $neikurc
    else
        [ -f $neikurc ] && host="$(cat $neikurc)"
    fi
fi
if [ -z "$host" ]
then
    host="$(hostname)"
fi
# TODO: delete $neikurc after logout

# PS1 => user@host:pwd[#$]
if [ `whoami` = root ]
then
    export PS1="\[\e[31;1m\]\u\[\e[0m\]@\[\e[32;1m\]$host\[\e[0m\]:\[\e[35;1m\]\w\[\e[0m\]\[\e[33;1m\]\$(__git_ps1)\[\e[0m\]# "
else
    export PS1="\[\e[31;1m\]\u\[\e[0m\]@\[\e[32;1m\]$host\[\e[0m\]:\[\e[35;1m\]\w\[\e[0m\]\[\e[33;1m\]\$(__git_ps1)\[\e[0m\]$ "
fi

# ipv4 addr <==> ip net-bytes
function ip2nb() # ip2nb 192.168.1.1 => 16885952
{
    local a=$(echo "$1" | cut -f1 -d.)
    local b=$(echo "$1" | cut -f2 -d.)
    local c=$(echo "$1" | cut -f3 -d.)
    local d=$(echo "$1" | cut -f4 -d.)
    echo $(((d<<24) | (c<<16) | (b<<8) | a))
}
function nb2ip() # nb2ip 16885952 => 192.168.1.1
{
    local a=$((($1 & 0xff000000) >> 24))
    local b=$((($1 & 0x00ff0000) >> 16))
    local c=$((($1 & 0x0000ff00) >> 8))
    local d=$(($1 & 0x000000ff))
    echo $d.$c.$b.$a
}

# nps <proc name>  -- 模糊查询进程信息
function nps()
{
    local cmd="$1"
    local fmt='uid,euid,pid,ppid,tty,lstart,cmd'
    if [ -n "$cmd" ] ; then
       ps -e -o $fmt | head -n1; ps -e -o $fmt | grep --color "$cmd"
   else
       ps -e -o $fmt
   fi
}
alias p='nps'
alias ps?='nps'

# nid uid  -- 根据uid查询username
function nid()
{
    local uid="$1"
    awk -F':' '{printf "%s\t%s\n", $1,$3}' /etc/passwd | grep "\<$uid\>" | cut -f1
}
alias id?='nid'

# 使用VI模式命令行编辑环境，同时保留默认模式的快捷键(EMACS)
set -o vi
bind -m vi-insert '\C-a':beginning-of-line  # Ctrl+a 移动光标到行首
bind -m vi-insert '\C-b':backward-char      # Ctrl+b 左移光标
bind -m vi-insert '\C-d':delete-char        # Ctrl+d 删除当前光标字符
bind -m vi-insert '\C-e':end-of-line        # Ctrl+e 移动光标到行末
bind -m vi-insert '\C-f':forward-char       # Ctrl+f 右移光标
bind -m vi-insert '\C-l':clear-screen       # Ctrl+l 清屏
bind -m vi-insert '\C-x':vi-movement-mode   # Ctrl+x 相当于esc键
